import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const MoneySchema = new mongoose.Schema({
    fromUserId: String,
    toUserId: String,
    money: Number,
    msg: String,
    payTool: Number, // 0 支付宝; 1 微信; 2 余额
    createTime: Number
});

MoneySchema.methods.saveMoney = function (money, cb) {
    money.createTime = moment().unix();
    this.model('money').insertMany([money], cb);
};

MoneySchema.methods.getMoneys = function (query, cb) {
    const { current = 1, pageSize = 10, ...leftQuery } = query;
    const moneyModel = this.model('money');
    moneyModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        moneyModel.find(leftQuery).skip((current - 1) * pageSize).limit(pageSize).exec((err, moneys) => cb(err, moneys, count, hasMore));
    });
};

MoneySchema.methods.getAllMoneys = function (query, cb) {
    // this.model('money').find(query, { name: 1, _id: 0 }, cb);
    this.model('money').find(query, cb);
};

MoneySchema.methods.getMoney = function (query, cb) {
    this.model('money').findOne(query, cb);
};

MoneySchema.methods.updateMoney = function (money, cb) {
    const _id = money._id;
    delete money._id;
    this.model('money').findOneAndUpdate({ _id }, { $set: money }, cb);
};

MoneySchema.methods.removeMoneys = function (moneyIds, cb) {
    this.model('money').remove({ _id: { $in: moneyIds } }, cb);
};

export default db.model('money', MoneySchema);